package fi.internetix.ck;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DefaultNodePrinter implements NodePrinter {
  
  public void processNode(Node node, StringBuilder output) {
    Element element = (Element) node;
    String tagName = NodePrinterUtils.extractLowercaseTagName(element.getTagName());
    output.append('<');
    output.append(tagName);

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
      processAttribute(element, attrs.item(i), output);
    }

    NodeList children = element.getChildNodes();
    if (children.getLength() == 0) {
      output.append("/>");
    }
    else {
      output.append('>');
      for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        NodePrinter nodePrinter = NodePrinterUtils.getNodePrinter(child);
        if (nodePrinter != null) {
          nodePrinter.processNode(child, output);
        }
      }
      output.append("</");
      output.append(tagName);
      output.append('>');
    }
  }

  public void processAttribute(Element element, Node attribute, StringBuilder output) {
    String attrName = NodePrinterUtils.extractLowercaseTagName(attribute.getNodeName());
    String attrValue = attribute.getNodeValue();
    if (attrValue != null) {
      output.append(' ');
      output.append(attrName);
      output.append("=\"");
      output.append(attrValue);
      output.append("\"");
    }
  }

}
